import React, { createRef, useEffect, useState, useRef, ChangeEvent, useContext } from 'react';
import { Container, Button, Image, FormGroup, Form, InputGroup, FormLabel, ButtonGroup} from 'react-bootstrap';
import SunEditor, { buttonList } from 'suneditor-react';
import 'suneditor/dist/css/suneditor.min.css';
import SunEditorCore from 'suneditor/src/lib/core';
import {useLocation, useNavigate} from 'react-router-dom';
import {toast} from 'react-toastify';
import {enc} from 'crypto-js';
import blogservice from '../../../services/blogservice';
import "./index.css"
import networkutil from '../../../utils/network';
import { PopupDialog } from '../../../components/common';
import { UserHelper } from '../../../helper';
import AuthenticationContext from '../../../context/Context';

function PostEditor(){
    
    const location = useLocation();
    const [isEdit,setIsEdit] = useState(false);
    const [showEditBtn,setShwoEditBtn] = useState(false);
    //TODO:to complete the text editor.
    /**@type {React.MutableRefObject<SunEditor>}*/
    const editor = useRef<SunEditorCore>();
    const [article,setArticle] = useState<any>();
    const [activeTitle,setActiveTitle] = useState(false);
    const [articleTitle,setArticleTitle] = useState("");

    const [activeDesc,setActiveDesc] = useState(false);
    const [articleDesc,setArticleDesc] = useState("");

    const [fullcontent,setFullContent] = useState<string|undefined>('');
    const [content,setContent] = useState<string|undefined>('');

    const iframeRef = createRef<HTMLIFrameElement>();

    const navigate = useNavigate();

    const {userInfo} = useContext(AuthenticationContext);


    const getSunEditorInstance = (sunEditor:SunEditorCore)=>{
        editor.current = sunEditor;
    }

    useEffect(()=>{
        const atk = (location.state||{}).article||{};
        setArticle(atk);
        setArticleTitle(atk.title);
        setArticleDesc(atk.description);
        if(atk.articleid){
            setShwoEditBtn(true)
            fetch(atk.url).then(res=>res.text()).then((res)=>{
                setFullContent(res);
                const result:RegExpMatchArray|null = res.match(/(<!--article-content\s*start-->)([.|\s\S]*?)(<!--article-content\s*end-->)/g,)
                if(result && result.length > 0){
                    var updatedContent = result[0].replace(/(<!--article-content\s*start-->)|(<!--article-content\s*end-->)|\s{2,}/g,"");
                    setContent(updatedContent);    
                }
            }).catch((err)=>{
                console.debug(err)
            })
        }else{
            setIsEdit(true);
        }
        
    },[]);


    const onFocusTitle = ()=> {
        setActiveTitle(true);
    }
    const onBlurTitle = ()=> {
        setActiveTitle(false);
    }

    const onChangeTitle = (event:ChangeEvent)=> {
        var target:any = event.target;
        var newValue = target?.value;
        setArticleTitle(newValue);
        console.debug(`article title: ${newValue}`);
    }

    const onFocusDesc = ()=> {
        setActiveDesc(true);
    }
    const onBlurDesc = ()=> {
        setActiveDesc(false);
    }

    const onChangeDesc = (event:ChangeEvent)=> {
        var target:any = event.target;
        var newValue = target.value
        setArticleDesc(newValue);
        console.debug(`article description: ${newValue}`);    
    }

    const onDraft = ()=> {
        publish(true);
    }
    const onPublish = ()=> {
        publish(false);
    }

    const onPaste = (event: ClipboardEvent, cleanData: string, maxCharCount: boolean)=> {
        //TODO；paste image
        const imageData:DataTransferItemList|undefined = event.clipboardData?.items;
        var items:Array<DataTransferItem> = [].slice.call(imageData).filter(function(item:any){
            return item.type.indexOf("image") !== -1;
        })
        if(items.length === 0){
            return;
        }
        const item:DataTransferItem = items[0];
        const file:File|null = item.getAsFile();
        if(file){
        }
    }

    const publish = (isDraft:boolean=false)=> {
        //TODO: reduce image size if image size larger than 200kb;
        console.debug("publishing...");
        var encodedHtml = buildHtml({title:articleTitle,description:articleDesc});
        console.debug("draft: got html:\n"+encodedHtml);
        var url = "";
        if(article && article.articleid && article.url){
            url = article.url
        }
        blogservice.createOrUpdateArticle({
            userid:userInfo.userid,
            title:articleTitle,
            description:articleDesc,
            content:encodedHtml,
            url:url,
            articleid:article.articleid,
            isDraft:isDraft,
        }).then(()=>{
            navigate("/blog")
        }).catch((err)=>{
            console.debug(err);
        })
    }

    const buildHtml = (htmlInfo:{title:string,keywords?:string,description:string}) => {
        var htmlContent = editor.current?.getContents(true)||"";
        setContent(htmlContent)
        //TODO:adjust html template to fit device.
        var kw = htmlInfo.keywords||htmlInfo.title||htmlInfo.description||""
       let htmlStr =  `
        <!doctype html>
            <html>
                <head>
                    <meta charset="utf-8">
                    <meta name="viewport" content="width=device-width,height=device-height,initial-scale=1,user-scalable=0,minimum-scale=1,maximum-scale=1"/>
                    <meta name="keywords" content="${kw}"/>
                    <meta name="description" content="${htmlInfo.description}"/>
                    <title>${htmlInfo.title}</title>
                    <style>
                       div img{
                         max-width:100%;
                         height: auto;
                         width: auto;
                       }
                       video{
                        margin:10px;
                        width:100%;
                       }
                       .title{
                            text-align:center;
                       }
                    </style>
                    <link href="/assets/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"/>
                    <script src="/assets/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
                </head>
                <body>
                    <h1 class='title'>${htmlInfo.title}</h1>
                    <!--article-content start-->
                    ${htmlContent}
                    <!--article-content end-->
                </body>
        </html>`;
        // console.debug("draft: got  html:\n"+htmlStr);
        // let wordarray = enc.Utf8.parse(htmlStr);
        // let base64Str = enc.Base64.stringify(wordarray);
        return htmlStr
    }
    const getEditMode = ()=>{
        return (<Container fluid style={{display:"flex",flexDirection:"column"}}>
        <Form>
             {/* <Form.></> */}
             <InputGroup>
                 <Form.FloatingLabel label={'标题'}>
                     <Form.Control type='input' 
                        defaultValue={articleTitle}
                         placeholder='Title'
                         onChange={onChangeTitle}
                         onFocus={onFocusTitle} 
                         onBlur={onBlurTitle} />
                 </Form.FloatingLabel>
             </InputGroup>
         </Form>
         <Form className='mt-3'>
             {/* <Form.></> */}
             <InputGroup>
                 <Form.FloatingLabel label={'描述'}>
                     <Form.Control type='input' 
                         defaultValue={articleDesc}
                         placeholder='Desc'
                         onChange={onChangeDesc}
                         onFocus={onFocusDesc} 
                         onBlur={onBlurDesc} />
                 </Form.FloatingLabel>
             </InputGroup>
         </Form>
         <FormLabel className='m-2'>正文</FormLabel>
         <SunEditor
             height='calc(100vh*0.65)'
             autoFocus={true}
             getSunEditorInstance={getSunEditorInstance}
             setOptions={{height:"50",buttonList:[
                 ['bold','underline','italic','fontSize','formatBlock','fontColor',
                 'hiliteColor','align','horizontalRule','list','table','link','image','video',
                 'showBlocks','codeView','fullScreen','removeFormat','undo','redo','save'],
             ]}}
             placeholder='Please input you article here'
             setContents={content||""}
             appendContents={""}
             onSave={onDraft}
             onPaste={onPaste}
         />
         <ButtonGroup style={{width:200}} className='mt-3 align-self-end'>
             <Button variant='outline-info' onClick={onDraft}>暂存草稿</Button>
             <Button onClick={onPublish}>发布</Button>
         </ButtonGroup>
     </Container>)    
    }

    const getReadonlyMode = ()=> {
        return (<Container fluid style={{width:"100vw",height:"100vh"}}>
            {article && article.url && <iframe 
            ref={iframeRef} srcDoc={fullcontent} style={{width:"100%",height:"100%"}}/>}
        </Container>)
    }

    const onPressEdit = ()=> {
        setIsEdit(!isEdit)
    }

    const onDelete = ()=> {
        PopupDialog.showBSPopup({message:"Are you sure you want to delete this post?"},()=>{
            blogservice.removeArticles(userInfo.userid,[article.articleid]).then(()=>{
                toast("delete articles successfully!",{autoClose:50,});
                setTimeout(()=>{
                    navigate(-1);
                },500)
            }).catch((err)=>{
                PopupDialog.showBsError(err);
            })
        })
    }

    //TODO: add keywords support
    return <Container fluid className='d-flex flex-column m-0 p-0'>
        <div className='align-self-end'>{showEditBtn ?<Button variant='link' size='sm' className='my-2' onClick={onPressEdit}>{isEdit ? "Cancel":"Edit"}</Button>:null}
        {showEditBtn && <Button variant='link text-danger' onClick={onDelete}>Delete</Button>}</div>
        {(isEdit ? getEditMode():getReadonlyMode())}
    </Container>
}

export default PostEditor;